package com.atguigu.tingshu.user.strategy.impl;

import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserVipService;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserVipServiceMapper;
import com.atguigu.tingshu.user.mapper.VipServiceConfigMapper;
import com.atguigu.tingshu.user.strategy.ItemTypeStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import org.joda.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author atguigu-mqx
 * @ClassName VipStrategy
 * @description: TODO
 * @date 2025年04月26日
 * @version: 1.0
 */
@Service("1003")
public class VipStrategy implements ItemTypeStrategy {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private VipServiceConfigMapper vipServiceConfigMapper;

    @Autowired
    private UserVipServiceMapper userVipServiceMapper;
    //  不判断类型怎么找到这个实现类?
    @Override
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        //  购买 vip user_vip_service ; vip续期
        UserVipService userVipService = new UserVipService();
        //  赋值：
        userVipService.setUserId(userPaidRecordVo.getUserId());
        userVipService.setOrderNo(userPaidRecordVo.getOrderNo());
        userVipService.setStartTime(new Date());
        //  过期时间;
        //  case 1: 用户第一次购买 user_info.is_vip=0； case 2: 用户续期；
        UserInfo userInfo = userInfoMapper.selectById(userPaidRecordVo.getUserId());
        //  创建系统时间：
        Date currentTime = new Date();
        //  获取用户购买的时长;
        Long vipServiceConfigId = userPaidRecordVo.getItemIdList().get(0);
        VipServiceConfig vipServiceConfig = vipServiceConfigMapper.selectById(vipServiceConfigId);
        Integer serviceMonth = vipServiceConfig.getServiceMonth();
        //  判断用户是否购买过vip;
        if (1 == userInfo.getIsVip() && userInfo.getVipExpireTime().after(new Date())) {
            //  续期;
            //  时长;serviceMonth
            currentTime = new LocalDateTime(userInfo.getVipExpireTime()).plusMonths(serviceMonth).toDate();
        } else {
            //  如果没有续期;
            currentTime = new LocalDateTime(currentTime).plusMonths(serviceMonth).toDate();
        }
        //  设置过期时间
        userVipService.setExpireTime(currentTime);
        //            //  购买vip 的时候出错!
        //            int i = 1 / 0;
        // 保存数据
        userVipServiceMapper.insert(userVipService);
        //  更新用户vip状态：
        userInfo.setIsVip(1);
        userInfo.setVipExpireTime(currentTime);
        userInfoMapper.updateById(userInfo);
    }
}
